import React from "react";
// 导入路由
import { Route } from "react-router-dom";
//导入antd-mobile组件
import { TabBar } from "antd-mobile";
// 导入内容组件
import News from "../News/news.js";
import Index from "../Index/index.js";
import Profile from "../Profile/profile.js";
import HouseList from "../HouseList/houselist.js";
// 导入组件自己的样式文件
import "./home.less";

// map渲染TabBar.Item使用的属性
const tabBarItems = [
  {
    title:"首页",
    icon:"icon-ind",
    path:"/home"
  },
  {
    title:"找房",
    icon:"icon-findHouse",
    path:"/home/list"
  },
  {
    title:"资讯",
    icon:"icon-infom",
    path:"/home/news"
  },
  {
    title:"我的",
    icon:"icon-my",
    path:"/home/profile"
  }
]

export default class Home extends React.Component {
  constructor(props) {
    super(props);
    // 状态控制
    this.state = {
      selectedTab: props.location.pathname, // 默认选中的tab
    };
  }

  // Home组件更新时
  componentDidUpdate( prevProps){
    // 在该生命周期函数中更新状态必须要有逻辑判断 否则会导致递归更新
    if (prevProps.location.pathname === this.props.location.pathname ) return ;
    this.setState(()=>({
      selectedTab:this.props.location.pathname
    }))
  }
  
  // map渲染TabBarItems
  renderTabBarItems = () => {
    return tabBarItems.map(item => {
      return (
        /* TabBar.Item 就是TabBar中的每个项*/
        <TabBar.Item
          title={item.title}
          key={item.title}
          icon={<i className={`iconfont ${item.icon}`} />}
          selectedIcon={<i className={`iconfont ${item.icon}`} />}
          // selected 该item项是否高亮
          selected={this.state.selectedTab === item.path}
          onPress={() => {
            this.setState({
              selectedTab: item.path,
            });
            this.props.history.push(item.path);
          }}
        />
      )
    })
  }

  render() {
    return (
      <div className={"home"}>
        <Route path={"/home/news"} component={News} />
        <Route exact path={"/home"} component={Index} />
        <Route path={"/home/list"} component={HouseList} />
        <Route path={"/home/profile"} component={Profile} />
        <TabBar
          unselectedTintColor="#888"
          tintColor="#21b97a"
          barTintColor="white"
          noRenderContent={true}
        >
          {this.renderTabBarItems()}
        </TabBar>
      </div>
    );
  }
}
